import { defineStore } from 'pinia'

interface IState {
  widgetList: widgetConfig[];
  widgetConfig: any;
  screenConfig: any;
  uuid: string;
  ctx?: CanvasRenderingContext2D | null;
  commit: (type: string, payload: any) => void;
}
export interface setConfig {
  uuid: string;
  propsName: string;
  value: any
}

export const useStore = defineStore<string, IState>('Store', {
  state: () => ({
    widgetList: [],
    widgetConfig: {},
    screenConfig: {},
    uuid: '',
    commit(type, payload) {
      (this as any)[type](payload)
    }
  }),
  actions: {
    ADD_WIDGET(widget: widgetConfig) {
      this.widgetList.push(widget)
    },
    REMOVE_WIDGET(uid: string) {
      this.widgetList = this.widgetList.filter(widget => widget.uuid !== uid)
    },
    GET_WIEGET(uid: string): widgetConfig {
      const widgets = this.widgetList.filter(widget => widget.uuid !== uid)
      if (widgets.length > 0) {
        return widgets[0]
      }
      return this.widgetList[0]
    },
    SET_WIDGET_CONFIG(props: setConfig) {
      if (!this.widgetConfig[props.uuid]) {
        this.widgetConfig[props.uuid] = {}
      }
      this.widgetConfig[props.uuid][props.propsName] = props.value
    },
    SET_SCREEN_CONFIG(props: any) {
      this.screenConfig = props
    },
    SET_DEFAULT_WIDGET_CONFIG(props: any) {
      this.widgetConfig[props.uuid] = props.defaultValues
    },
    SET_UUID(uuid: string) {
      this.uuid = uuid
    },
    SET_CTX(ctx: CanvasRenderingContext2D) {
      this.ctx = ctx
    }
  }
})